import {createRouter, createWebHistory} from "vue-router";
import {getToken} from "@/api/cookie.js";
import {isTokenExpired} from "@/api/utils.js";
import {ElMessage} from "element-plus";

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/",
            redirect: "/user/system/question"
        },
        {
            path: "/user/login",
            component: () => import("@/components/views/Login.vue")
        },
        {
            path: "/user/answer",
            component: () => import("@/components/views/Answer.vue")
        },
        {
            path: "/user/system",
            component: () => import("@/components/views/System.vue"),
            children: [
                {
                    path: "question",
                    component: () => import("@/components/views/Question.vue"),
                    meta: {showBanner: true}
                },
                {
                    path: "contest",
                    component: () => import("@/components/views/Contest.vue"),
                    meta: {showBanner: true}
                },
                {
                    path: "some/contest",
                    component: () => import("@/components/views/UserContest.vue"),
                    meta: {showBanner: false}
                },
                {
                    path: "user-info",
                    component: () => import("@/components/views/UserInfo.vue"),
                    meta: {showBanner: false}
                },
                {
                    path: "message",
                    component: () => import("@/components/views/Message.vue"),
                    meta: {showBanner: false}
                }
            ]
        },
        {
            path: "/:pathMatch(.*)*",
            name: "NotFound",
            component: () => import("@/components/views/404.vue"),
        },
    ]
})

router.beforeEach((to, from, next) => {
    const token = getToken()

    if (to.name === "NotFound") {
        next();
        return;
    }

    if (token && !isTokenExpired(token)) {
        // 此时有token && token 处于有效期
        if (to.path === '/user/login') {
            // 这里如果访问 / 页面，会进行重定向到 /login 页面
            next({
                path: '/user/system/'
            })
        } else {
            // 访问其他页面，直接访问即可
            next()
        }
    } else {
        // 此时 token不存在 | token过期
        if (to.path !== '/user/login') {
            ElMessage.error("用户登录信息已过期")
            // 重定向到 /login 页面
            next({
                path: '/user/login'
            })
        } else {
            next()
        }
    }
})

export default router